package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.UserDataIsolation;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.ProjectGroupDeviceResultVO;
import com.ruoyi.system.domain.vo.ProjectGroupDeviceVO;
import com.ruoyi.system.domain.vo.ProjectGroupParamVO;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.mapper.ProjectDeviceGroupMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 产品分组Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-10
 */
@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Service
public class ProjectDeviceGroupServiceImpl implements IProjectDeviceGroupService {
    @Autowired
    private ProjectDeviceGroupMapper projectDeviceGroupMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceGroupService deviceGroupService;


    @Autowired
    private IPointCheckService pointCheckService;

    @Autowired
    private IDevicePointCheckConfigService devicePointCheckConfigService;

    @Autowired
    private IPointCheckConfigService pointCheckConfigService;

    /**
     * 查询产品分组
     *
     * @param id 产品分组ID
     * @return 产品分组
     */
    @Override
    @UserDataIsolation(tableAlias = "g")
    public ProjectDeviceGroup selectTblProjectDeviceGroupById(Integer id) {
        if (StringUtils.isEmpty(id)){
            throw new CustomException("项目分组Id不能为空！");
        }
        ProjectDeviceGroup param = new ProjectDeviceGroup();
        param.setId(id);
        ProjectDeviceGroup projectDeviceGroup = projectDeviceGroupMapper.selectTblProjectDeviceGroupById(param);
        if (projectDeviceGroup == null) {
            throw new CustomException("没有查询到分组信息");
        }
        List<Device> deviceList = projectDeviceGroupMapper.getDeviceByGroupId(id);
        deviceList = CollectionUtils.isEmpty(deviceList) ? new ArrayList<>() : deviceList;
        projectDeviceGroup.setDeviceList(deviceList);
        return projectDeviceGroup;
    }

    /**
     * 查询产品分组列表
     *
     * @param projectDeviceGroup 产品分组
     * @return 产品分组
     */
    @Override
    @UserDataIsolation(tableAlias = "g")
    public List<ProjectDeviceGroup> selectTblProjectDeviceGroupList(ProjectDeviceGroup projectDeviceGroup) {
        return projectDeviceGroupMapper.selectTblProjectDeviceGroupList(projectDeviceGroup);
    }

    /**
     * 新增产品分组
     *
     * @param projectDeviceGroup 产品分组
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean saveProjectDeviceGroup(ProjectDeviceGroup projectDeviceGroup) {
        if (projectDeviceGroupMapper.insertTblProjectDeviceGroup(projectDeviceGroup) <= 0) {
            throw new CustomException("项目分组添加失败");
        }
        return true;
    }

    /**
     * 保存产品与项目分组的关系
     *
     * @param ids       产品Ids
     * @param groupId   项目分组Id
     */
    private void saveDeviceGroup(List<Integer> ids, Integer groupId) {
        //增加产品与项目分组的关系
        if (!CollectionUtils.isEmpty(ids) && groupId != null) {
            Set<Integer> idList = new HashSet<>(ids);
            for (Integer deviceId : idList) {
                DeviceGroup deviceGroup = new DeviceGroup();
                deviceGroup.setDeviceId(deviceId);
                deviceGroup.setGroupId(groupId);
                deviceGroupService.insertTblDeviceGroup(deviceGroup);
            }
        }

    }


    /**
     * 修改产品分组
     *
     * @param projectDeviceGroup 产品分组
     * @return 结果
     */
    @Override
    @UserDataIsolation
    public Boolean updateProjectDeviceGroup(ProjectDeviceGroup projectDeviceGroup) {
        if (projectDeviceGroup == null || projectDeviceGroup.getId() == null) {
            throw new CustomException("修改失败！产品分组或产品分组Id不能为空!");
        }
        projectDeviceGroupMapper.updateTblProjectDeviceGroup(projectDeviceGroup);
        return true;
    }

    @Override
    @Transactional
    public void bindDevice(ProjectDeviceGroup projectDeviceGroup) {
        if (projectDeviceGroup == null){
            throw new CustomException("项目分组信息不能为空");
        }
        if (projectDeviceGroup.getId() == null){
            throw new CustomException("项目分组Id不能为空");
        }
        //删除该分组下面的所有产品
        deviceGroupService.deleteTblDeviceGroupById(projectDeviceGroup.getId());
        //添加产品与项目分组的关系
        saveDeviceGroup(projectDeviceGroup.getIds(), projectDeviceGroup.getId());
        pointCheckConfigUpdate(projectDeviceGroup);
    }

    /**
     * 修改分组产品对应绑定的计划
     *
     */
    private void pointCheckConfigUpdate(ProjectDeviceGroup projectDeviceGroup) {
        Long companyId = projectDeviceGroup.getCompanyId();
        Integer id = projectDeviceGroup.getId();
        PointCheck pointCheck = new PointCheck();
        pointCheck.setGroupId(id);
        //查询分组关联的计划
        List<PointCheck> pointChecks = pointCheckService.queryGroupList(pointCheck);
        if(!CollectionUtils.isEmpty(pointChecks)){
            List<Integer> oldIds = projectDeviceGroup.getOldIds();
            List<Integer> ids = projectDeviceGroup.getIds();
            //需要添加的产品
            List<Integer> add = ids.stream().filter(account -> !oldIds.contains(account)).collect(Collectors.toList());
            //需要删除的产品
            List<Integer> delete = oldIds.stream().filter(account -> !ids.contains(account)).collect(Collectors.toList());
            //计划
            for (PointCheck p: pointChecks
                 ) {
                String items = p.getItems();
                JSONObject jsonObject = JSONUtil.parseObj(items);
                if(!CollectionUtils.isEmpty(add)){
                    //任务
                    for (Integer a:add
                    ) {
                        //添加产品点检配置到计划
                        QueryVo queryVo = new QueryVo();
                        queryVo.filters.put("company_id", companyId);
                        queryVo.filters.put("device_id", a);
                        List<DevicePointCheckConfig> devicePointCheckConfigs = devicePointCheckConfigService.queryList(queryVo);
                        ArrayList<String> strings = new ArrayList<>();
                        if(!CollectionUtils.isEmpty(devicePointCheckConfigs)){

                            //任务-点检配置
                            for (DevicePointCheckConfig deviceConfig: devicePointCheckConfigs
                                 ) {

                                PointCheckConfig pointCheckConfig = new PointCheckConfig();
                                pointCheckConfig.setPointId(p.getId());
                                pointCheckConfig.setDeviceId(a);
                                pointCheckConfig.setCheckConfigId(deviceConfig.getId());
                                pointCheckConfig.setCompanyId(companyId);
                                pointCheckConfig.setCreateBy(p.getCreateBy());
                                pointCheckConfig.setCreateTime(p.getCreateTime());
                                Boolean add1 = pointCheckConfigService.add(pointCheckConfig);
                                if(!add1){
                                    throw new CustomException("修改失败");
                                }
                            }
                        }

                        //修改计划的items
                        List<Map<String, Object>> list = devicePointCheckConfigService.typeItemEnumCheck(queryVo);
                        for (Map l: list
                             ) {
                            List<Map<String, Object>> children =(List) l.get("children");
                            for (Map c: children
                                 ) {
                                strings.add((String) c.get("label"));
                            }
                        }
                        //修改计划的Items
                        jsonObject.accumulate(a+"",strings);
                        PointCheck pointCheck1 = new PointCheck();
                        pointCheck1.setId(p.getId());
                        pointCheck1.setItems(JSONUtil.toJsonStr(jsonObject));
                        Boolean aBoolean1 = pointCheckService.updateInfo(pointCheck1);
                        if(!aBoolean1){
                            throw new CustomException("修改失败");
                        }


                    }
                }
                if(!CollectionUtils.isEmpty(delete)){
                    for (Integer d:delete
                    ) {
                        //删除产品点检配置到计划
                        QueryVo queryVo = new QueryVo();
                        queryVo.filters.put("pointId", p.getId());
                        queryVo.filters.put("deviceId", d);
                        Boolean aBoolean = pointCheckConfigService.deletePointIdDeviceId(queryVo);
                        if(!aBoolean){
                            throw new CustomException("修改失败");
                        }
                        //修改计划的Items
                        jsonObject.remove(d+"");
                        PointCheck pointCheck1 = new PointCheck();
                        pointCheck1.setId(p.getId());
                        pointCheck1.setItems(JSONUtil.toJsonStr(jsonObject));
                        Boolean aBoolean1 = pointCheckService.updateInfo(pointCheck1);
                        if(!aBoolean1){
                            throw new CustomException("修改失败");
                        }


                    }
                }
            }


        }





    }


//    /**
//     * 批量删除产品分组
//     *
//     * @param ids 需要删除的产品分组ID
//     * @return 结果
//     */
//    @Override
//    public int deleteTblProjectDeviceGroupByIds(Long[] ids) {
//        return tblProjectDeviceGroupMapper.deleteTblProjectDeviceGroupByIds(ids);
//    }

    /**
     * 删除产品分组信息
     *
     * @param id 产品分组ID
     * @return 结果
     */
    @Override
    @UserDataIsolation
    @Transactional
    public Boolean deleteProjectDeviceGroupById(Integer id) {
        //删除产品分组
        projectDeviceGroupMapper.deleteTblProjectDeviceGroupById(id);
        //删除产品和项目分组之前的关系
        deviceGroupService.deleteTblDeviceGroupById(id);
        return true;
    }

    @Override
    public ProjectGroupDeviceResultVO queryBindDevice(ProjectGroupParamVO projectGroupParamVO) {
        List<ProjectGroupDeviceVO> projectGroupDeviceVOS = projectDeviceGroupMapper.queryBindDevice(projectGroupParamVO);
        if (CollectionUtils.isEmpty(projectGroupDeviceVOS)){
            ProjectGroupDeviceResultVO resultVO = new ProjectGroupDeviceResultVO();
            resultVO.setNotBindDevices(new ArrayList<>());
            resultVO.setBindDevices(new ArrayList<>());
            return resultVO;
        }
        List<ProjectGroupDeviceVO> bindDevices = new ArrayList<>();
        List<ProjectGroupDeviceVO> notBindDevices = new ArrayList<>();
        projectGroupDeviceVOS.stream().forEach(a ->{
            if (a.getDeviceGroupId() == null){
                notBindDevices.add(a);
            }else {
                bindDevices.add(a);
            }
        });
        ProjectGroupDeviceResultVO resultVO = new ProjectGroupDeviceResultVO();
        resultVO.setBindDevices(bindDevices);
        resultVO.setNotBindDevices(notBindDevices);
        return resultVO;
    }

//    @Override
//    //根据分组id查询该分组下的所有产品
//    public List<TblDevice> selectTblDeviceGroupByGid(Long groupId) {
//        return tblDeviceMapper.selectTblDeviceGroupByGid(groupId);
//    }
//
//    @Override
//    public Boolean addGroupDevice(ProjectDeviceGroup projectDeviceGroup) {
//        return null;
//    }
}

